import os
import openai
from dotenv import load_dotenv
import requests
from openai import OpenAI

from http import HTTPStatus
from dashscope import ImageSynthesis
import os

load_dotenv()

api_key = "sk-645190d55952481685d26e2ef8303915"
client = OpenAI(
    # 若没有配置环境变量，请用百炼API Key将下行替换为：api_key="sk-xxx",
    api_key=api_key,
    base_url="https://dashscope.aliyuncs.com/compatible-mode/v1"
)


def generate_six_panel_comic(text, style="default"):
    """生成六格漫画"""
    try:
        # 1. 使用GPT将文本分解为6个连贯的场景描述
        system_prompt = (
            "你是一个专业漫画编剧。将以下故事分解为6个关键场景，"
            "每个场景用1-2句话描述，包含场景、角色表情和动作。"
            "格式为：1. 描述... 2. 描述... 3. 描述..."
        )

        response = client.chat.completions.create(
            model="deepseek-r1",
            messages=[
                {"role": "system", "content": system_prompt},
                {"role": "user", "content": f"故事内容:{text}\n\n请生成6个漫画分镜:"}
            ],
            temperature=0.7,
            max_tokens=1000
        )

        description = response.choices[0].message.content.strip()

        # 2. 解析出6个场景描述
        scenes = []
        for i in range(1, 7):
            start_idx = description.find(f"{i}.")
            end_idx = description.find(f"{i + 1}.") if i < 6 else len(description)
            scene = description[start_idx:end_idx].strip()
            scene = scene.replace(f"{i}.", "").strip()
            scenes.append(scene)

        # 3. 为每个场景生成图像
        image_urls = []
        for i, scene in enumerate(scenes):
            try:
                # 添加风格提示词
                style_prompts = {
                    "default": "comic book style",
                    "shonen": "shonen manga style, dynamic",
                    "shoujo": "shoujo manga style, delicate",
                    "chibi": "chibi style, cute"
                }
                style_prompt = style_prompts.get(style, "")

                # 调用Midjourney API
                headers = {
                    "Authorization": f"Bearer {MIDJOURNEY_API_KEY}",
                    "Content-Type": "application/json"
                }

                payload = {
                    "prompt": f"{scene} --ar 3:4 --v 5 --style 4b {style_prompt} --panel {i + 1}/6",
                    "aspect_ratio": "3:4"
                }

                response = requests.post(
                    "https://api.midjourney.com/v1/generate",
                    headers=headers,
                    json=payload
                )

                if response.status_code == 200:
                    image_urls.append(response.json().get("url"))
                else:
                    print(f"Error generating panel {i + 1}: {response.text}")
                    image_urls.append(None)

            except Exception as e:
                print(f"Error generating panel {i + 1}: {e}")
                image_urls.append(None)

        return {
            "description": description,
            "scenes": scenes,
            "image_urls": image_urls,
            "panel_count": 6
        }

    except Exception as e:
        print(f"Error in six panel generation: {e}")
        return None


def generate_description(text, style="default"):
    """使用GPT生成漫画描述"""
    try:
        # 根据风格定制提示词
        style_prompts = {
            "default": "将以下文本转换为适合生成漫画的分镜描述，包含场景、角色表情和动作:",
            "shonen": "以少年漫画风格将以下文本转换为漫画分镜描述，强调动作和热血场景:",
            "shoujo": "以少女漫画风格将以下文本转换为漫画分镜描述，注重情感表达和精美场景:",
            "seinen": "以青年漫画风格将以下文本转换为漫画分镜描述，注重写实和深度叙事:",
            "chibi": "以Q版漫画风格将以下文本转换为幽默可爱的漫画分镜描述:"
        }

        prompt = style_prompts.get(style, style_prompts["default"]) + f"\n\n{text}"

        response = client.chat.completions.create(
            model="deepseek-r1",  # 模型列表：https://help.aliyun.com/zh/model-studio/getting-started/models
            messages=[
                {"role": "system", "content": "你是一个专业的漫画脚本作家。生成四宫格漫画，"},
                {'role': 'user', 'content': prompt}
            ]
        )

        print(response)

        return response.choices[0].message.content.strip()
    except Exception as e:
        print(f"Error generating description: {e}")
        return None


def generate_images(description, num_panels=1):
    prompt = "一间有着精致窗户的花店，漂亮的木质门，摆放着花朵"

    print('----sync call, please wait a moment----')
    rsp = ImageSynthesis.call(api_key=api_key,
                              model="wanx2.0-t2i-turbo",
                              prompt=description,
                              n=4,
                              size='768*768'
                              )
    print('response: %s' % rsp)
    if rsp.status_code == HTTPStatus.OK:
        # 在当前目录下保存图片
        urls = []
        for result in rsp.output.results:
            urls.append(result.url)
        return urls
    else:
        print('sync_call Failed, status_code: %s, code: %s, message: %s' %
              (rsp.status_code, rsp.code, rsp.message))


def split_description_to_panels(description, num_panels):
    """将长描述分割为多个面板提示"""
    sentences = description.split('. ')
    panels = []
    sentences_per_panel = max(1, len(sentences) // num_panels)

    for i in range(num_panels):
        start = i * sentences_per_panel
        end = start + sentences_per_panel
        panel = ". ".join(sentences[start:end])
        if panel:
            panels.append(panel)

    # 如果分割后数量不足，补充提示
    while len(panels) < num_panels:
        panels.append(f"漫画场景，风格一致，与以下内容相关: {description[:100]}...")

    return panels[:num_panels]
